import { computed, ref, watch, type ComputedRef } from "vue";
import type { IGdp } from "./useFetchIGdp";
import gsap from "gsap";

export type IBar = {
  color: string;
  size: number;
};

export type IBars = IGdp & IBar;

const colors = ["#334552", "#b34335", "#6e9fa5", "#a2c3a5", "#c8846c"];
export default function useGdp(gdpRef: ComputedRef<IGdp[]>, maxSize: number) {
  const bars = ref<IBars[]>([]);
  const maxValue = computed(() => {
    if (gdpRef.value.length) {
      return Math.max(...gdpRef.value.map((v) => v.value));
    }
    return 0;
  });

  const barsTarget = computed<IBars[]>(() => {
    return gdpRef.value.map((v, i) => ({
      ...v,
      color: colors[i % colors.length],
      size: (v.value / maxValue.value) * maxSize,
    }));
  });

  watch(
    barsTarget,
    () => {
      for (let i = 0; i < barsTarget.value.length; i++) {
        if (!bars.value[i]) {
          bars.value[i] = {
            ...barsTarget.value[i],
            size: 0,
            value: 0,
          };
        }

        // bars.value[i]中的属性 逐步变化到barsTarget.value[i]
        gsap.to(bars.value[i], {
          ...barsTarget.value[i],
          duration: 1,
        });
      }
    },
    { deep: true }
  );

  return {
    bars,
  };
}
